package com.tiger.cloud.controller.weChat;

import com.tiger.cloud.common.mybatis.BaseController;
import com.tiger.cloud.filter.IgnoreAuth;
import com.tiger.cloud.model.ext.WeChatSign;
import com.tiger.cloud.util.Response;
import com.tiger.cloud.util.ResponseUtil;
import com.tiger.cloud.util.weChat.Sha1Util;
import com.tiger.cloud.util.weChat.WeChatSignUtil;
import io.swagger.annotations.Api;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping(value = "wxChat")
@Api(value = "微信接口", tags = "微信接口")
public class WeChatAuthController extends BaseController {

     private final static String TOKEN = "examcrm";
    @RequestMapping(value = "protal", method = RequestMethod.GET)
    @ResponseBody
    @IgnoreAuth
    @CrossOrigin
    public String  wechatCore(HttpServletRequest request, HttpServletResponse response) throws Exception {

        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        String signature = request.getParameter("signature");
        String nonce = request.getParameter("nonce");
        String timestamp = request.getParameter("timestamp");
        String echostr = request.getParameter("echostr");
        System.out.println("signature = "+signature+"====  nonce = "+nonce+"====  timestamp = "+timestamp+"====  echostr = "+echostr);
        List<String> list = new ArrayList();
        list.add(nonce);
        list.add(timestamp);
        list.add(TOKEN);

        String  sign = Sha1Util.SHA1(list);
        boolean flag = sign.equals(signature);
        System.out.println(flag);

        PrintWriter out = response.getWriter();
        if (flag) {
            out.print(echostr);
       }
        out.close();
        return null;
    }
    @RequestMapping(value = "getSignTrue", method = RequestMethod.POST)
    @ResponseBody
    @CrossOrigin
    @IgnoreAuth
    public Response getSignTrue(@RequestBody WeChatSign weChatSign) throws Exception {
        Map<String, String> result = new HashMap<String, String>();
        String url = URLDecoder.decode(weChatSign.getUrl());
        result = WeChatSignUtil.sign(url);
        if(result.size() == 0){
           return ResponseUtil.error("签名失败");
        }

        return ResponseUtil.ok(result);
    }

}
